package com.zy.project.system.user.controller;

import com.zy.core.common.utils.StringUtils;
import com.zy.core.data.jpa.support.entity.page.Pagination;
import com.zy.core.util.page.LayuiPageResult;
import com.zy.core.util.page.Result;
import com.zy.core.util.servlet.ServletUtils;
import com.zy.core.web.BaseController;
import com.zy.core.web.entity.JsonResult;
import com.zy.project.system.user.entity.SystemUser;
import com.zy.project.system.user.manager.SystemUserManager;
import io.swagger.annotations.Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Package: core.web.system.user
 * <p>
 * Description： TODO
 * <p>
 * Author: zhangyu
 * <p>
 * Date: Created in 2018-9-25 20:29
 * <p>
 * Company: mingtu
 * <p>
 * Copyright: Copyright (c) 2018
 * <p>
 * Version: 0.0.1
 * <p>
 * Modified By:
 */
@Controller
@RequestMapping("/system/user")
@Api(description = "系统用户接口")
public class SystemUserController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(BaseController.class);

    private static final String BASE_URL = "system/user/";


    @Autowired
    private SystemUserManager systemUserManager;

    @GetMapping("/index")
    @ApiIgnore
    public String index(HttpServletRequest request, HttpServletResponse response, ModelMap model){
        return BASE_URL + "index";
    }

    @GetMapping("/add")
    @ApiIgnore
    public String add(HttpServletRequest request, HttpServletResponse response, ModelMap model){
        return BASE_URL + "add";
    }

    @GetMapping("/edit/{id}")
    @ApiIgnore
    public String edit(HttpServletRequest request, HttpServletResponse response, ModelMap model,
                       @PathVariable("id") String id){
        if(StringUtils.isNotEmpty(id)){
            model.put("user",systemUserManager.findById(id));
        }
        return BASE_URL + "edit";
    }

    @GetMapping("/view/{id}")
    @ApiIgnore
    public String view(HttpServletRequest request, HttpServletResponse response, ModelMap model,
                       @PathVariable("id") String id){
        if(StringUtils.isNotEmpty(id)){
            model.put("user",systemUserManager.findById(id));
        }
        return BASE_URL + "view";
    }

    /**
     * 获取列表数据
     * @param request
     * @param response
     * @param model
     * @param page 页码
     * @param limit 每页数据量
     */
    @GetMapping
    @ApiIgnore
    public void list(HttpServletRequest request, HttpServletResponse response, ModelMap model,
                       @RequestParam(value = "page", required = true) int page,
                       @RequestParam(value = "limit", required = true) int limit){
        LayuiPageResult result = new LayuiPageResult();
        try {
            Pagination<SystemUser> pageBean = systemUserManager.findAll(page, limit);
            result.init(pageBean);
        } catch (Exception e) {
            logger.error("获取列表信息失败",e);
            e.printStackTrace();
        } finally {
            ServletUtils.renderJson(response,result.readerJson());
        }
    }

    /**
     * 执行删除
     * @param request
     * @param response
     * @param ids
     */
    @DeleteMapping
    public void delete(HttpServletRequest request, HttpServletResponse response,String[] ids){
        Result result = new Result();
        try {
            systemUserManager.deleteByIds(ids);
            result.suc();
        } catch (Exception e) {
            logger.error("删除出现异常!",e);
            result.error("删除出现异常!");
            e.printStackTrace();
        }finally {
            ServletUtils.renderJson(response,result.readerJson());
        }
    }

    /**
     * 执行更新
     * @param request
     * @param response
     * @param permission
     */
    @PutMapping
    public void update(HttpServletRequest request, HttpServletResponse response, SystemUser user){
        JsonResult result = new JsonResult();
        try {
            if(null == user){
                result.failure("未获取任何数据!");
            }else if(StringUtils.isEmpty(user.getId())){
                result.failure("id不能为空!");
            }else{
                systemUserManager.update(user);
                result.success();
            }
        } catch (Exception e) {
            logger.error("更新出现异常!",e);
            result.error("更新出现异常!");
            e.printStackTrace();
        }finally {
            ServletUtils.renderJson(response,result.toJsonString());
        }
    }

    /**
     * 新增
     * @param request
     * @param response
     * @return
     */
    @PostMapping
    public void save(HttpServletRequest request, HttpServletResponse response, SystemUser user){
        JsonResult result = new JsonResult();
        try {
            StringBuilder sb = new StringBuilder();
            if(user == null){
                sb.append("未获取到任何信息!");
            }else if(StringUtils.isEmpty(user.getUsername())){
                sb.append("用户名不能为空!");
            }else if (StringUtils.isEmpty(user.getPassword())){
                sb.append("密码不能为空!");
            }else if(user.getStatus().getValue() == null){
                sb.append("用户状态不能为空!");
            }

            if(sb.length() > 0){
                result.failure(sb.toString());
            }else{
                result.success();
            }
        } catch (Exception e) {
            result.error("新增出现异常!");
            logger.error("新增出现异常!",e);
            e.printStackTrace();
        } finally {
            String jsonString = result.toJsonString();
            ServletUtils.renderJson(response,jsonString);
        }
    }


}
